package com.sg.activiti.web;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sg.activiti.ext.Todo;
import com.sg.activiti.service.MyActivitiService;
import com.sg.common.empty.core.EpUtil;
import com.sg.common.login.entity.Member;
import com.sg.common.login.service.OrgMemberService;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
import com.sg.common.utils.StrUtil;

@Repository
@Controller
public class MyActivitiController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	MyActivitiService service;

	@Autowired
	OrgMemberService omservice;
	
	/**
	 * 任务列表
	 * 
	 * 
	 * @param leave
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "/acti/common/history")
	@ResponseBody
	public Object history(HttpServletRequest request)
			throws ClassNotFoundException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {

		String proInsId = request.getParameter("_proInsId");
		List<HistoricTaskInstance> hl = service.history(proInsId);
		StringBuilder tdSb=new StringBuilder();
		tdSb=tdSb.append(" style='font-size:13px;'");
		StringBuilder bodySb = new StringBuilder();
		bodySb.append("<table class='horTable' border='1px;' style='width:100%;'>");
		if (hl != null && hl.size() > 0) {
			bodySb.append("<tr><td").append(tdSb).append(">流程节点</td><td").append(tdSb).append(">审批意见</td><td").append(tdSb).append(">启动时间</td><td").append(tdSb).append(">处理时间</td><td").append(tdSb).append(">处理人</td></tr>");
			for (HistoricTaskInstance ht : hl) {
				String comment = "";
				List<Comment> comments = taskService
						.getTaskComments(ht.getId());
				if (comments.size() > 0) {
					comment = comments.get(0).getFullMessage();
				}
				String assignee=ht.getAssignee();
				if(StringUtils.isNotEmpty(assignee))
				{
					Member member=omservice.findMemberByCode(assignee);
					if(member!=null)
						assignee=assignee+"("+member.descr+")";
				}
				
				if(!StrUtil.requestParamsNotEmpty(assignee))
				{
					assignee=service.getGroupID(ht.getId());
				}
				
				bodySb.append("<tr><td").append(tdSb).append(">")
						.append(ht.getName())
						.append("</td><td").append(tdSb).append(">")
						.append(comment)
						.append("</td><td").append(tdSb).append(">")
						.append(DateTimeUtils.formatDate(ht.getStartTime(),
								"yy-MM-dd HH:mm"))
						.append("</td><td").append(tdSb).append(">")
						.append(DateTimeUtils.formatDate(ht.getEndTime(),
								"yy-MM-dd HH:mm")).append("</td><td").append(tdSb).append(">")
						.append(assignee).append("</td></tr>");
				
			}
		} else {
			bodySb.append("无信息");
		}
		bodySb.append("</table>");
		bodySb.append("<a href='acti/common/pic?_proInsId=" + proInsId
				+ "' target='_blank'>查看流程图片</a>");
		ModelAndView res = EpUtil.commonView(bodySb, new StringBuilder(),
				request);
		return res;
	}

	@RequestMapping(value = "/acti/common/pic")
	@ResponseBody
	public void pic(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String proInsId = request.getParameter("_proInsId");
		
		InputStream in=service.getpic(proInsId);

        //声明输出流，但是要从HttpServletResponse中获取才管用  
        BufferedOutputStream bout = new BufferedOutputStream(response.getOutputStream());  
        //从输入流到输出流  
        try {    
            byte b[] = new byte[1024];    
            int len = in.read(b);    
            while (len > 0) {    
                bout.write(b, 0, len);    
                len = in.read(b);    
            }    
        } catch (Exception e) {    
            if (e.getClass().getName().equals(    
                    "org.apache.catalina.connector.ClientAbortException")) {    
                // 用户取消下载任务报的错，无需处理    
            } else {    
                throw e;    
            }    
        } finally {    
            bout.close();    
            in.close();    
        }  
	}
	
	@RequestMapping(value = "/acti/common/start")
	@ResponseBody
	public Object add(HttpServletRequest request) throws Exception {
		String className = request.getParameter("className");
		String bussId = request.getParameter("bussId");
		Map<String, Object> variables = new HashMap<String, Object>();
		// TODO 查找现数据没有start流程过。不然不让启动
		ProcessInstance processInstance = service.startWorkflow(className,
				bussId, variables, request);
		logger.info("流程已启动，流程ID：{}", processInstance.getId());
		return "commited,flow started!";
	}

	/**
	 * 任务列表
	 * 
	 * 
	 * @param leave
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "/acti/common/mytask")
	@ResponseBody
	public Object taskList(HttpSession session, HttpServletRequest request)
			throws ClassNotFoundException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		String userCode = request.getParameter("_userCode");
		if (StringUtils.isEmpty(userCode)) {
			userCode = Constant.getSessionMemberCode(request);
		}
		List<Todo> todos = service.findTodoTasks(userCode);
		Collections.sort(todos,new dateComparator());
		StringBuilder bodySb = new StringBuilder();
		bodySb.append("<tr><td><a target='_blank' style='color:red' href=\"http://10.10.38.228/course/30\">在线帮助手册，请点我！</a></td></tr>");
		bodySb.append("  <table class='horTable' border='1px;' style='width:95%;'>");
		bodySb.append("<tr><th colspan='5'>").append(userCode)
				.append("的待处理任务</th><td> <input type='button' id='reload' style=' width: 100px; border: 1px solid #2576A8;letter-spacing: 9px;font-size: 18px;' name='reload' value='刷新' onclick='reloadtab()'></td></tr>");
		bodySb.append("<tr><td>任务ID</td><td>流程名称</td><td>摘要</td><td>节点名称</td><td>接收时间</td><td>马上处理</td></tr>");
		for (Todo t : todos) {
			bodySb.append("<tr><td>").append(t.getId()).append("</td><td>")
					.append(t.getProcname()).append("</td><td>")
					.append(t.getDescr()).append("</td><td>")
					.append(t.getTaskname()).append("</td><td>")
					.append(t.getCdate())
					.append("</td><td><a target='_blank' href=\"")
					.append(t.getLink()).append("\">马上处理</a></td></tr>");
		}
		bodySb.append("</table>");
		StringBuilder jssb= new StringBuilder();
		jssb.append("function reloadtab(){location.reload() ;};");
		ModelAndView res = EpUtil.commonView(bodySb, jssb,
				request);
		return res;
	}

	// 自定义比较器：按接收时间来排序  
    static class dateComparator implements Comparator {  
        public int compare(Object object1, Object object2) {// 实现接口中的方法  
        	Todo t1 = (Todo) object1; // 强制转换  
        	Todo t2 = (Todo) object2;  
            return t2.getCdate().compareTo(t1.getCdate());  
        }  
    }  
    
    
    
  /**
   * 
   * 流程实例管理
   * @param session
   * @param request
   * @return
 * @throws Exception 
   */
	@RequestMapping(value = "/acti/common/instanceManage")
	@ResponseBody
	public Object instanceManage(HttpSession session, HttpServletRequest request)
			throws Exception {
		List<HistoricProcessInstance> hpilList=service.findProInstance();

		StringBuilder bodySb = new StringBuilder();
		bodySb.append("<table class='horTable' border='1px;' style='width:80%;'>");
		bodySb.append("<tr><th colspan='5'>").append("")
				.append("流程实例列表</th> </tr>");
		bodySb.append("<tr><td>实例ID</td><td>流程名称</td><td>启动时间</td><td>结束时间</td><td>马上处理</td></tr>");
		for (HistoricProcessInstance hip : hpilList) {
			if(StringUtils.equals(hip.getId(), "645034"))
				{
				 int a=1;
				
				}
			ProcessDefinition pd=service.findProDefById(hip.getProcessDefinitionId());
			bodySb.append("<tr><td>").append(hip.getId()).append("</td><td>")
					.append(pd.getName()).append("</td><td>")
					.append(DateTimeUtils.formatDate(hip.getStartTime(),
							"yyyy-MM-dd HH:mm")).append("</td><td>")
					.append(DateTimeUtils.formatDate(hip.getEndTime(),
							"yyyy-MM-dd HH:mm")).append("</td><td>")
					//.append("</td><td><a target='_blank' href=\"")
					.append(hip.getDeleteReason())
					//.append("\">马上处理</a></td></tr>");
					.append("</td></tr>");
		}
		bodySb.append("</table>");
		ModelAndView res = EpUtil.commonView(bodySb, new StringBuilder(),
				request);
		return res;
	}
	
	@Autowired
	protected TaskService taskService;

	/**
	 * 完成任务
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/acti/common/complete", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Object complete(HttpServletRequest request) {
		try {
			String taskId = request.getParameter("_taskId");
			service.complete(taskId, request);
			return "succ";
		} catch (Exception e) {
			return "error!" + e.getMessage();
		}
	}

	/**
	 * 拟稿人取消流程
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/acti/common/endProcess", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Object endProcess(HttpServletRequest request) {
		try {
			String taskId = request.getParameter("_taskId");
			TaskEntity task=service.findTaskById(taskId);
			if(task!=null)
			 taskService.addComment(taskId, task.getProcessInstanceId(), "发起人取消流程");
			service.endProcess(taskId,request);
			return "succ";
		} catch (Exception e) {
			return "error!" + e.getMessage();
		}
	}

	/**
	 * 管理员结束流程实例
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/acti/InstanceManage/endInstanc", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Object endInstanc(HttpServletRequest request) {
		try {
			String instanceID = request.getParameter("id");
			service.endInstanc(instanceID,request);
			return "succ";
		} catch (Exception e) {
			return "error!" + e.getMessage();
		}
	}
	
	@RequestMapping(value = "/acti/InstanceManage/getBpmnModel", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Object getBpmnModel(HttpServletRequest request) {
			String processInstanceId = request.getParameter("id");
			
			BpmnModel model = service.getBpmnModel(processInstanceId);
			StringBuilder bodySb = new StringBuilder();
			bodySb.append("<table class='horTable' border='1px;' style='width:80%;'>");
			bodySb.append("<tr><th colspan='5'>").append("")
					.append("流程实例节点列表</th> </tr>");
			bodySb.append("<tr><td>节点ID</td><td>节点名称</td><td>操作</td></tr>");
			if(model != null) {  
			    Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();  
			    
			    for(FlowElement e : flowElements) {  
			    	String nameString=e.getClass().getName();
			    	if(StringUtils.equals(e.getClass().getName(),"org.activiti.bpmn.model.UserTask"))
			    	bodySb.append("<tr><td>").append(e.getId()).append("</td><td>")
					.append(e.getName()).append("</td><td><a target='_blank' href=\"acti/InstanceManage/jump?_activityId=")
					.append(e.getId())
					.append("&_processInstanceId=")
					.append(processInstanceId)
					.append("\">跳转至此</a></td></tr>");
			    }  
			}
			bodySb.append("</table>");
			ModelAndView res = EpUtil.commonView(bodySb, new StringBuilder(),
					request);
			return res;
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/acti/InstanceManage/jump", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Object jump(HttpServletRequest request) {
		try {
			String processInstanceId = request.getParameter("_processInstanceId");
			String activityId = request.getParameter("_activityId");
			service.jumpProcess(processInstanceId, activityId, request);
			return "succ";
		} catch (Exception e) {
			return "error!" + e.getMessage();
		}
	}
}
